import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Copy, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Slider } from '@/components/ui/slider';
import { Checkbox } from '@/components/ui/checkbox';
import { SimpleTitlebar } from '@/components/SimpleTitlebar';

const PasswordGeneratorPage: React.FC = () => {
  const [password, setPassword] = useState('');
  const [length, setLength] = useState([16]);
  const [includeUppercase, setIncludeUppercase] = useState(true);
  const [includeLowercase, setIncludeLowercase] = useState(true);
  const [includeNumbers, setIncludeNumbers] = useState(true);
  const [includeSymbols, setIncludeSymbols] = useState(true);
  const [excludeSimilar, setExcludeSimilar] = useState(false);
  const [excludeAmbiguous, setExcludeAmbiguous] = useState(false);
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" } | null>(null);

  // Generate initial password
  useEffect(() => {
    generatePassword();
  }, []);

  const generatePassword = () => {
    const charset = {
      uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
      lowercase: 'abcdefghijklmnopqrstuvwxyz',
      numbers: '0123456789',
      symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?'
    };

    let availableChars = '';
    if (includeUppercase) availableChars += charset.uppercase;
    if (includeLowercase) availableChars += charset.lowercase;
    if (includeNumbers) availableChars += charset.numbers;
    if (includeSymbols) availableChars += charset.symbols;

    if (availableChars === '') {
      setPassword('');
      return;
    }

    // Remove similar characters if requested
    if (excludeSimilar) {
      availableChars = availableChars.replace(/[il1Lo0O]/g, '');
    }

    // Remove ambiguous characters if requested
    if (excludeAmbiguous) {
      availableChars = availableChars.replace(/[{}[\]()\/\\'"~,;.<>]/g, '');
    }

    let generatedPassword = '';
    for (let i = 0; i < length[0]; i++) {
      generatedPassword += availableChars.charAt(Math.floor(Math.random() * availableChars.length));
    }

    setPassword(generatedPassword);
  };

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(password);
      setToast({ message: '密码已复制到剪贴板', type: 'success' });
      setTimeout(() => setToast(null), 2000);
    } catch (error) {
      setToast({ message: '复制失败', type: 'error' });
      setTimeout(() => setToast(null), 2000);
    }
  };

  return (
    <div className="h-screen bg-background flex flex-col">
      {/* Simple Titlebar */}
      <SimpleTitlebar title="密码生成器" />

      {/* Content */}
      <div className="flex-1 p-4 space-y-6 overflow-y-auto">
        {/* Generated Password */}
        <div className="space-y-2">
          <Label htmlFor="password">生成的密码</Label>
          <div className="flex gap-2">
            <Input
              id="password"
              value={password}
              readOnly
              className="font-mono text-sm"
            />
            <Button
              variant="outline"
              size="sm"
              onClick={copyToClipboard}
              className="px-3"
            >
              <Copy className="w-4 h-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={generatePassword}
              className="px-3"
            >
              <RefreshCw className="w-4 h-4" />
            </Button>
          </div>
        </div>

        {/* Length Slider */}
        <div className="space-y-3">
          <Label>密码长度: {length[0]}</Label>
          <Slider
            value={length}
            onValueChange={setLength}
            max={64}
            min={4}
            step={1}
            className="w-full"
          />
        </div>

        {/* Character Options */}
        <div className="space-y-3">
          <Label>包含字符类型</Label>
          <div className="grid grid-cols-2 gap-3">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="uppercase"
                checked={includeUppercase}
                onCheckedChange={(checked) => setIncludeUppercase(checked as boolean)}
              />
              <Label htmlFor="uppercase" className="text-sm">大写字母 (A-Z)</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="lowercase"
                checked={includeLowercase}
                onCheckedChange={(checked) => setIncludeLowercase(checked as boolean)}
              />
              <Label htmlFor="lowercase" className="text-sm">小写字母 (a-z)</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="numbers"
                checked={includeNumbers}
                onCheckedChange={(checked) => setIncludeNumbers(checked as boolean)}
              />
              <Label htmlFor="numbers" className="text-sm">数字 (0-9)</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="symbols"
                checked={includeSymbols}
                onCheckedChange={(checked) => setIncludeSymbols(checked as boolean)}
              />
              <Label htmlFor="symbols" className="text-sm">符号 (!@#$...)</Label>
            </div>
          </div>
        </div>

        {/* Advanced Options */}
        <div className="space-y-3">
          <Label>高级选项</Label>
          <div className="space-y-2">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="excludeSimilar"
                checked={excludeSimilar}
                onCheckedChange={(checked) => setExcludeSimilar(checked as boolean)}
              />
              <Label htmlFor="excludeSimilar" className="text-sm">排除相似字符 (il1Lo0O)</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="excludeAmbiguous"
                checked={excludeAmbiguous}
                onCheckedChange={(checked) => setExcludeAmbiguous(checked as boolean)}
              />
              <Label htmlFor="excludeAmbiguous" className="text-sm">
                排除模糊字符 ({' '} {'{'} {'}'} {'['} {']'} {'('} {')'} {'/'} {'\\'} {"'"} {'"'} {'~'} {','} {';'} {'.'} {'<'} {'>'} )
              </Label>
            </div>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex gap-2 pt-2">
          <Button
            onClick={generatePassword}
            className="flex-1"
          >
            <RefreshCw className="w-4 h-4 mr-2" />
            重新生成
          </Button>
          <Button
            variant="outline"
            onClick={copyToClipboard}
            className="flex-1"
          >
            <Copy className="w-4 h-4 mr-2" />
            复制密码
          </Button>
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: 20 }}
          className={`fixed bottom-4 right-4 px-4 py-2 rounded-md shadow-lg z-[10000] ${
            toast.type === 'success' 
              ? 'bg-green-500 text-white' 
              : 'bg-red-500 text-white'
          }`}
        >
          {toast.message}
        </motion.div>
      )}
    </div>
  );
};

export default PasswordGeneratorPage;
